//
//  HomeView.swift
//  ShouChong
//
//  Created by 陈友文 on 2024/6/19.
//

import SwiftUI
import Alamofire

struct HomeView: View {
    @AppStorage("user_name") var userName:String = ""
    @AppStorage("curren_main_color") var currentMainColor = "color_main_01"
    @State var startOffset:CGFloat = 0
    @State var currentOffset:CGFloat = 0
    var dateClickBlock:(() -> Void)
    var playClickBlock:(() -> Void)
    @State var showMoreCalendar:Bool = false
    @ObservedObject var vm:HomeViewModel = HomeViewModel()
    @ObservedObject var phoneVM:PhoneViewModel = PhoneViewModel()
    @State var showLoading:Bool = false
    
    var body: some View {
        ScrollView {
            VStack(alignment: .leading,spacing:8) {
                Text("你好")
                    .modifier(MainTextModifier(fontSize: 24, fontWeight: .bold, foreColor: Color("color_text_black")))
                Text(userName)
                    .modifier(MainTextModifier(fontSize: 18, fontWeight: .bold, foreColor: Color(currentMainColor)))
            }
            .frame(maxWidth: .infinity,alignment:.leading)
            .padding(.horizontal,20)
            .padding(.top,10)
            YWCalendarView(showMoreCalendar: $showMoreCalendar, didSelect: { date in
//                DPrint(date)
                showLoading = true
                vm.getUserDataWithDate(date: date) { 
                    showLoading = false
                }
            })
            .background(Color("color_bg"))
            .frame(width: kScreenWidth - 40,height: showMoreCalendar ? 400:120)
            .padding(.horizontal,20)
            .padding(.bottom,10)
            .zIndex(3)
            .offset(y:currentOffset < 233 - 80 ? 233 - 80 - currentOffset :0)
            .overlay {
                GeometryReader { reader -> Color in
                    let minY = reader.frame(in: .global).minY
                    DispatchQueue.main.async {
                        currentOffset = minY
                    }
                    return Color.clear
                }.frame(width: 0, height:0)
            }
            HStack{
                Image(systemName: "arrowtriangle.down.fill")
                    .resizable()
//                    .aspectRatio(contentMode: .fit)
                    .frame(width: 14,height: 6)
                    .foregroundColor(Color(currentMainColor))
                    .rotationEffect(showMoreCalendar ? .degrees(180) : .degrees(0))
            }.onTapGesture {
                let generator = UIImpactFeedbackGenerator(style: .light)
                generator.prepare()
                generator.impactOccurred()
                withAnimation {
                    showMoreCalendar.toggle()
                }
            }
            .padding(.bottom,10)

//            VStack {
//                Image("home_no_data")
//                    .resizable()
//                    .aspectRatio(contentMode: .fill)
//                    .frame(width:200,height: 200)
//                    .padding(.bottom,10)
//                Text("当日暂无数据~")
//                    .modifier(MainTextModifier(fontSize: 16, fontWeight: .bold, foreColor:  Color("color_text_black")))
//            }
//            Spacer(minLength: 120)
            craeteDayDate()
                .onTapGesture {
                    let generator = UIImpactFeedbackGenerator(style: .light)
                    generator.prepare()
                    generator.impactOccurred()
                    self.dateClickBlock()
                }
            DaySentenceView()
            ShakeButton(
                label: Text("开 始")
                    .modifier(MainButtonModifier(width: kScreenWidth - 50))
            ) {
                self.playClickBlock()
            }.padding(.top,10)
//            .padding(.bottom,0)
            
            
        }.onAppear{
            showLoading = true
            vm.getUserDataWithDate(date: Date()) {
                showLoading = false
            }
        }
        .overlay(alignment: .center) {
            if showLoading {
                ProgressView()
            }
        }
    }
    
    func craeteDayDate() -> some View {
        HStack {
            VStack {
                RoundedRectangle(cornerRadius: 24)
                    .fill(Color("color_white"))
                    .frame(width: 48,height:48)
                    .overlay {
                        Text("⏳")
                    }
                Text("\(vm.model.duration == "" ? "0" : vm.model.duration)")
                    .modifier(MainTextModifier(fontSize: 18, fontWeight: .bold, foreColor: Color("color_text_black")))
                    .padding(.vertical,5)
                
                Text("时长")
                    .modifier(MainTextModifier(fontSize: 14, fontWeight:.medium, foreColor: Color("color_text_black").opacity(0.6)))
            }
            .frame(width: (kScreenWidth - 70) / 2,height: 240)
            .background(Color("color_home_01").opacity(0.6))
            .cornerRadius(30)
            .padding(.trailing,5)
            VStack {
                HStack {
                    RoundedRectangle(cornerRadius: 24)
                        .fill(Color("color_white"))
                        .frame(width: 48,height:48)
                        .overlay {
                            Text("❤️")
                        }
                    VStack(alignment:.leading) {
                        Text("\(vm.model.duration == "" ? "0" : vm.model.heartRate)")
                            .modifier(MainTextModifier(fontSize: 18, fontWeight: .bold, foreColor: Color("color_text_black")))
                            .padding(.bottom,2)
                        
                        Text("心率")
                            .modifier(MainTextModifier(fontSize: 14, fontWeight:.medium, foreColor: Color("color_text_black").opacity(0.6)))
                    }.padding(.leading,2)
                }
                .frame(width: (kScreenWidth - 70) / 2,height: 110)
                    .background(Color("color_home_02").opacity(0.6))
                    .cornerRadius(30)
                Spacer()
                HStack {
                    RoundedRectangle(cornerRadius: 24)
                        .fill(Color("color_white"))
                        .frame(width: 48,height:48)
                        .overlay {
                            Text("💪🏻")
                        }
                    VStack(alignment:.leading) {
                        Text("\(vm.model.count == "" ? "0" : vm.model.count)")
                            .modifier(MainTextModifier(fontSize: 18, fontWeight: .bold, foreColor: Color("color_text_black")))
                            .padding(.bottom,2)
                        Text("次数")
                            .modifier(MainTextModifier(fontSize: 14, fontWeight:.medium, foreColor: Color("color_text_black").opacity(0.6)))
                    }.padding(.leading,2)
                }
                .frame(width: (kScreenWidth - 70) / 2,height: 110)
                    .background(Color("color_home_03").opacity(0.6))
                    .cornerRadius(30)
            }
            .padding(.leading,5)
        }
        .frame(width: kScreenWidth,height: 240)
       
    }

}


struct DaySentenceView:View {
    @AppStorage("curren_main_color") var currentMainColor = "color_main_01"
    @State var content:String = ""
    @State var count:Int = 0
    @State var adVM:InterstitialViewModel = InterstitialViewModel()
    @AppStorage("k_luleme_vip") var lulemeVIP:Bool = false
    var body: some View {
        VStack {
            Text(content)
                .minimumScaleFactor(0.5)
                .padding(10)
                .foregroundColor(Color(currentMainColor))
                .font(Font.system(size: 16, weight: .light, design: .rounded))
                .frame(width: kScreenWidth - 40, height: 120)
                .background(Color("color_home_03").opacity(0.6))
        }
        .background(Color("color_home_03").opacity(0.6))
        .cornerRadius(20)
        .padding(20)
        .onTapGesture {
            let generator = UIImpactFeedbackGenerator(style: .light)
            generator.prepare()
            generator.impactOccurred()

            if count >= 3 {
                if lulemeVIP {
                    getDaySentenceData()
                } else {
                    content = "不要再点了，再点我就要弹咯"
                }
                
                if count >= 4 {
                    if let isVip = UserDefaults.standard.value(forKey: kVipKey) as? Bool {
                        if !isVip {
                            adVM.showAd()
                        }
                    } else {
                        UserDefaults.standard.setValue(false, forKey: kVipKey)
                            adVM.showAd()
                    }
                    count = 0
                    getDaySentenceData()
                }
                
            } else {
                getDaySentenceData()
            }
            count += 1
        }
        .onAppear {
            
            Task {
                await adVM.loadAd()
            }
        }
        .onFirstAppear {
            getDaySentenceData()
        }
        
    }
    private func getDaySentenceData() {
        YWNetworkTool.share().requestJson(url: "info/getDaySentence", parameters: nil) { res in
            print(res)
            
            guard let res = res as? [String:Any],
                  let data = res["data"] as? [[String:String]]
            else {
                return
            }
            content = data.first?["content"] ?? ""
        } responseFailBlock: { error, code in
            DPrint(error)
        }


    }
}



public extension View {
    func onFirstAppear(perform action: @escaping () -> Void) -> some View {
        modifier(ViewFirstAppearModifier(perform: action))
    }
}

struct ViewFirstAppearModifier: ViewModifier {
    @State private var didAppearBefore = false
    private let action: () -> Void

    init(perform action: @escaping () -> Void) {
        self.action = action
    }

    func body(content: Content) -> some View {
        content.onAppear {
            guard !didAppearBefore else { return }
            didAppearBefore = true
            action()
        }
    }
}
